package com.smasher.modbus.weiqian;


import android.content.Context;
import android.content.res.Resources;
import android.util.Log;

import com.smasher.serialport.OnDataReceiveListener;
import com.smasher.serialport.SerialPortImpl;

import weiqian.hardware.SerialPortManager;

public class SerialPortWeiQian implements SerialPortImpl {

    public static final String TAG = "Weiqian";

    private final SerialPortManager manager;
    //====================
    private String path;
    private int baud;
    private int databits;
    private String parity;
    private int stopbits;

    private OnDataReceiveListener listener;

    private boolean isDebug = false;


    public SerialPortWeiQian() {
        manager = new SerialPortManager();
    }

    @Override
    public void init(String path, int baud, int databits, String parity, int stopbits) {
        this.path = path;
        this.baud = baud;
        this.databits = databits;
        this.parity = parity;
        this.stopbits = stopbits;
    }

    @Override
    public void open() {
        if (manager != null) {
            manager.open(path, baud, databits, parity, stopbits);
        }
    }

    @Override
    public void close() {
        if (manager != null) {
            manager.closeSerialPort();
        }
    }

    @Override
    public void write(byte[] sendData) {
        if (manager != null) {
            injectLog(sendData);
            manager.sendPacket(sendData);
        }
    }

    @Override
    public void read(byte[] sendData) {
        if (manager != null) {
            injectLog(sendData);
            manager.sendPacket(sendData);
        }
    }

    private void injectLog(byte[] sendData) {
        if (isDebug) {
            if (sendData != null) {
                StringBuilder build = new StringBuilder("[");
                for (int i = 0; i < sendData.length; i++) {
                    if (i == 0) {
                        build.append(sendData[i]);
                    } else {
                        build.append(",").append(sendData[i]);
                    }
                }
                build.append("]");
                Log.d(TAG, build.toString());
            }
        }
    }

    @Override
    public void addDataReceiveListener(OnDataReceiveListener listener) {
        this.listener = listener;
        if (manager != null) {
            manager.setOnDataReceiveListener((var1, var2) -> {
                if (this.listener != null) {
                    this.listener.onDataReceive(var1, var2);
                }
            });
        }
    }

    @Override
    public String[] getAllDevicesPath(Context context) {
        Resources resources = context.getResources();
        return resources.getStringArray(R.array.weiqian_port_name);
    }

    @Override
    public void setDebug(boolean b) {
        isDebug = b;
    }


}
